package com.crm.system.service.impl.customerManager;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DhPageInfo;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.DateUtil;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.memberManager.MonthDealCustomerQO;
import com.crm.model.qo.memberManager.MonthNewMemberQO;
import com.crm.model.vo.cluePoolManager.CluePoolVO;
import com.crm.model.vo.customerManager.NewSingleMemberStatisticsVO;
import com.crm.service.customerManager.NewMemberAnalyseDbService;
import com.crm.service.sys.UserAccountDbService;
import com.crm.system.service.customerManager.NewMemberAnalyseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author luojie
 * @date 2021/5/25 10:52
 */
@Service
public class NewMemberAnalyseServiceImpl implements NewMemberAnalyseService {

    @Autowired
    private NewMemberAnalyseDbService newMemberAnalyseDbService;

    @Override
    public List<JSONObject> getNewMemberMonthlyStatistics(Integer dateUnit) {
        List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
        SimpleDateFormat timeSdf = new SimpleDateFormat("yyyy");
        Calendar nowCal = Calendar.getInstance();
        String date = "";
        if (dateUnit == 1) {
            //本年
            date = timeSdf.format(nowCal.getTime());
        } else {
            //去年
            nowCal.add(Calendar.YEAR, -1);
            date = timeSdf.format(nowCal.getTime());
        }

        for (int i = 1; i < 13; i++) {
            String yearMonth = "";
            if (String.valueOf(i).length() == 1) {
                String month = "0" + i;
                yearMonth = date + "-" + month;
            } else {
                yearMonth = date + "-" + String.valueOf(i);
            }
            JSONObject mouthResult = new JSONObject();
            mouthResult.put("yearMonth", yearMonth);

            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
            //新增会员数
            long newNumberCount = newMemberAnalyseDbService.getNewMemberMonthlyStatistics(userAccount.getCompanyId(), yearMonth);
            mouthResult.put("newNumberCount", newNumberCount);
            //成交顾客数
            long dealCustomersNumber = newMemberAnalyseDbService.getDealCustomersNumber(userAccount.getCompanyId(), yearMonth);
            mouthResult.put("dealCustomersNumber", dealCustomersNumber);


            if (dealCustomersNumber != 0) {
                double progress = newNumberCount / (double) dealCustomersNumber;
                mouthResult.put("memberRecruitmentRate", String.format("%.2f", progress));
            } else {
                mouthResult.put("memberRecruitmentRate", 0);
            }
            jsonObjects.add(mouthResult);
        }
        return jsonObjects;
    }

    @Override
    public List<JSONObject> getEveryMonthlyNewMemberStatistics(String startDate, String endDate) {
        List<JSONObject> jsonObjects = new ArrayList<JSONObject>();


        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        //新增会员数
        HashMap<String, Long> monthNewMember = new HashMap<>();
        for (MonthNewMemberQO it : newMemberAnalyseDbService.selectMemberEveryMonthlyStatistics(userAccount.getCompanyId(), startDate, endDate)) {
            monthNewMember.put(it.getYearMonth(), it.getMemberCount());
        }


        //成交顾客数
        HashMap<String, Long> monthDealCustomers = new HashMap<>();
        for (MonthDealCustomerQO it : newMemberAnalyseDbService.getEveryMonthDealCustomersNumber(userAccount.getCompanyId(), startDate, endDate)) {
            monthDealCustomers.put(it.getYearMonth(), it.getDealCount());
        }


        // 组装返回值
        List<String> monthBetween = DateUtil.getMonthBetween(startDate, endDate);
        for (String dataStr : monthBetween) {
            JSONObject mouthResult = new JSONObject();
            mouthResult.put("yearMonth", dataStr);
            // 每月新增会员数
            long newNumberCount = monthNewMember.get(dataStr) == null ? 0 : monthNewMember.get(dataStr);
            mouthResult.put("newNumberCount", newNumberCount);

            // 每月成交用户数
            long dealCustomersNumber = monthDealCustomers.get(dataStr) == null ? 0 : monthDealCustomers.get(dataStr);
            mouthResult.put("dealCustomersNumber", dealCustomersNumber);

            if (0 != dealCustomersNumber) {
                double progress = newNumberCount / (double) dealCustomersNumber;
                mouthResult.put("memberRecruitmentRate", String.format("%.2f", progress));
            } else {
                mouthResult.put("memberRecruitmentRate", 0);
            }
            jsonObjects.add(mouthResult);
            //以上为业务数据
        }

        return jsonObjects;
    }

    @Override
    public DhPageInfo<NewSingleMemberStatisticsVO> getNewSingleMemberStatistics(Integer pageIndex, Integer pageSize) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        SimpleDateFormat timeSdf = new SimpleDateFormat("yyyy-MM");
        Calendar nowCal = Calendar.getInstance();
        //本月
        String yearMonth = timeSdf.format(nowCal.getTime());
        List<NewSingleMemberStatisticsVO> newSingleMemberStatisticsVOS = newMemberAnalyseDbService.getNewSingleMemberStatistics(yearMonth, userAccount.getCompanyId());
        PageInfo<NewSingleMemberStatisticsVO> pageInfo = new PageInfo<NewSingleMemberStatisticsVO>(newSingleMemberStatisticsVOS);
        return new DhPageInfo<NewSingleMemberStatisticsVO>(pageInfo, newSingleMemberStatisticsVOS);
    }

    @Override
    public DhPageInfo<NewSingleMemberStatisticsVO> selectNewSingleMemberStatisticsByContract(Integer pageIndex, Integer pageSize, String yearMonth, String contractType) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        List<NewSingleMemberStatisticsVO> newSingleMemberStatisticsVOS = newMemberAnalyseDbService.selectNewSingleMemberStatisticsByContract(yearMonth, userAccount.getCompanyId(), contractType);
        PageInfo<NewSingleMemberStatisticsVO> pageInfo = new PageInfo<NewSingleMemberStatisticsVO>(newSingleMemberStatisticsVOS);
        return new DhPageInfo<NewSingleMemberStatisticsVO>(pageInfo, newSingleMemberStatisticsVOS);
    }

    @Override
    public JSONObject getPercentageQuotaStatistics() {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        JSONObject result = new JSONObject();
        SimpleDateFormat timeSdf = new SimpleDateFormat("yyyy-MM");
        Calendar nowCal = Calendar.getInstance();
        //本月
        String yearMonth = timeSdf.format(nowCal.getTime());
        String contractType = "";
        //本月新增会员额度
        contractType = "2";   //会员新单合同
        //yearMonth = "2021-06";
        long memberQuota = newMemberAnalyseDbService.selectThisMonthPercentageQuotaStatistics(yearMonth, userAccount.getCompanyId(), contractType);
        result.put("memberQuota", memberQuota);
        //本月续费会员额度
        contractType = "4";   //会员续费合同
        long renewMemberQuota = newMemberAnalyseDbService.selectThisMonthPercentageQuotaStatistics(yearMonth, userAccount.getCompanyId(), contractType);
        result.put("renewMemberQuota", renewMemberQuota);
        //本月非会员额度
        contractType = "1";   //非会员合同
        long noMemberQuota = newMemberAnalyseDbService.selectThisMonthPercentageQuotaStatistics(yearMonth, userAccount.getCompanyId(), contractType);
        result.put("noMemberQuota", noMemberQuota);
        return result;
    }

}
